package freespiritsocial.io.user.util

import android.graphics.Bitmap
import freespiritsocial.io.user.base.App
import me.hgj.jetpackmvvm.ext.util.loge
import java.io.File
import java.io.FileOutputStream

/**
 * Created by hc. on 2020/4/23
 * Describe:
 */
object IFileUtils {

    /**
     * 写入一个文件
     */
    fun writeFile(name : String,value : String){
        try {
            val path = "${App.instance.getExternalFilesDir(null)?.absolutePath?:""}/app"
            val files = File(path)
            if (!files.exists()) {
                files.mkdirs()
            }
            val file = File(path, name)
            val createNewFile = file.createNewFile()
            if(createNewFile){
                val outStream = FileOutputStream(file)
                outStream.write(value.toByteArray())
                outStream.close()
            }

        }catch (e : java.lang.Exception){
            "E:$e".loge()
        }
    }
    fun saveFile(name: String , bitmap: Bitmap) : String{
        try {
            val path = "${App.instance.getExternalFilesDir(null)?.absolutePath?:""}/app"
            val files = File(path)
            if (!files.exists()) {
                files.mkdirs()
            }
            val file = File(path, name)
            val isExists = if(file.exists()){
                true
            }else{
                file.createNewFile()
            }
            if(isExists){
                val outStream = FileOutputStream(file)
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream)
                outStream.close()
            }
            return file.absolutePath
        }catch (e : java.lang.Exception){
            "E:$e".loge()
            return ""
        }
    }

    /** 保存文件 **/
    fun saveFile(name : String,arrayByte :ByteArray) : String{
        try {
            val path = "${App.instance.getExternalFilesDir(null)?.absolutePath?:""}/app"
            val files = File(path)
            if (!files.exists()) {
                files.mkdirs()
            }
            val file = File(path, name)
            val isExists = if(file.exists()){
                true
            }else{
                file.createNewFile()
            }
            if(isExists){
                val outStream = FileOutputStream(file)
                outStream.write(arrayByte)
                outStream.close()
            }
            return file.absolutePath
        }catch (e : java.lang.Exception){
            "E:$e".loge()
            return ""
        }
    }

    /** 创建目录 **/
    fun createFiles(name : String) : File?{
        try {
            val path = "${App.instance.cacheDir?.absolutePath?:""}/$name"
            val files = File(path)
            if (!files.exists()) {
                files.mkdirs()
            }
            return files
        }catch (e : java.lang.Exception){
           "E:$e".loge()
        }
        return null
    }

}